var catJSON;
var storeCategory;

var getDataObj = {
	getCategories : function() {
		storeCategory = new Ext.data.Store({
		    proxy: new Ext.data.HttpProxy({
				url: 'http://www.childdisabilityconnection.org/admin/ajaxDirector.php?handler=getCategories&siteArea=Shared Resource File&renderType=json'
		    }),
			
		    reader: new Ext.data.JsonReader({
		        root: 'Categories',
		        id: 'CatID'
		    }, [			
				{name: 'CatID', mapping: 'CatID'},
				{name: 'CatTitle',  mapping: 'CatTitle'}
		    ])		
		});	
		storeCategory.load();
		/*
		var params = 'handler=getCategories&siteArea=Shared Resource File&renderType=json';
		var ajaxResults = new Ajax.Request('http://www.childdisabilityconnection.org/admin/ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {				
				if (transport.responseText != 0) {
					getDataObj.catJSONGlobal(transport.responseText);
					catJSON = transport.responseText;
					var stringJSON = transport.responseText;
					var jsonObject = stringJSON.evalJSON();
					var totalItems = (jsonObject.Categories.length)-1;
					var catType    = jsonObject.CatType;
					for(var a=0;a<=totalItems;a++) {
						var catTitle = jsonObject.Categories[a].CatTitle;
						var catID    = jsonObject.Categories[a].CatID;
						$('fileCat').options[a] = new Option(catTitle,catID);	
					}
				}	
			}
		});
		*/
	},
	catJSONGlobal : function(stringJSON) {
		catJSON = stringJSON;
		
		storeCategory = new Ext.data.JsonStore({
			root:   'Categories',
			id:     'CatID',
	        fields: ['CatID', 'CatTitle'],
	        data :  catJSON
	    });
	    storeCategory.load();
	
	}
}

windowObj = {
	initWindow : function() {
		var win = window.nativeWindow;
	
		var opener   = Ext.air.NativeWindow.getRootHtmlWindow();
		var urlObj   = Ext.urlDecode(String(window.location).split('?')[1]);
		var fileID   = urlObj.fileID;
		var fileName = urlObj.fileName;
		
		win.title = 'File Details - '+fileName;
		
		var tb = new Ext.Toolbar({
		region: 'north',
		height:26,
		id:'main-tb',
		items:[{
			id:'cpl-btn', 
			iconCls: 'icon-mark-complete', 
			text: 'Mark Complete',
			handler: function(){
				
			}
		},'-',
			{iconCls: 'icon-delete-task', text: 'Delete', handler: function(){
				Ext.Msg.confirm('Confirm Delete', 'Are you sure you want to delete this task?', function(btn){
					if(btn == 'yes'){
						//opener.tx.data.tasks.remove(getTask());
						win.close();
					}
				});
			}}
			]
		});
		
		var catTree = new Ext.tree.TreePanel({
            useArrows: true,
            autoScroll: true,
            animate: true,
            enableDD: true,
            containerScroll: true,
            loader: new Ext.tree.TreeLoader({
                dataUrl: 'http://www.childdisabilityconnection.org/admin/ajaxDirector.php?handler=getCategories&siteArea=Shared Resource File&renderType=tree'
            })
        });
        
        // set the root node
        var root = new Ext.tree.AsyncTreeNode({
            text: 'Ext JS',
            draggable: false,
            id: 'source'
        });
        catTree.setRootNode(root);
        
        // render the tree
        root.expand();
        
        // treeSelector
        var treeField = new Ext.ux.TreeSelector({
            tree: catTree,
            maxHeight: 200,
            listenForLoad: false,
        });
		
		var catMain = new Ext.form.ComboBox({		
			fieldLabel:    'File Category',
			store:         storeCategory,
		    displayField:  'CatTitle',
		    valueField:    'CatID',
		    name:          'catMain',
		    typeAhead:     false,
		    mode:          'local',
		    emptyText:     'Select category...',
		    forceSelection:true,
		    selectOnFocus: true,
			width:         180,
			resizable:     true,
	        shadow:        false,
	        grow:          true,
	        growMax:       300,
	        growMin:       200,
	        listWidth:     200,
	        handleHeight:  12
		});
		
		var title = new Ext.form.TextField({
			fieldLabel: 'File Title',
	        name: 'title',
	        anchor: '100%'
	    });		
	
		var isPTIShared = new Ext.form.Checkbox({
			fieldLabel: false,
			boxLabel: 'This is a PTI Shared Resource',
			checked: false
		});	
		
		var description = new Ext.form.HtmlEditor({
	        hideLabel: true,
	        name: 'description',
	        anchor: '100% -95',  // anchor width by percentage and height by raw adjustment
	        onEditorEvent : function(e){
		        var t;
		        if(e.browserEvent.type == 'mousedown' && (t = e.getTarget('a', 3))){
		            t.target = '_blank';
		        }
		        this.updateToolbar();
		    }
	    });
	
		var form = new Ext.form.FormPanel({
			region:'center',
	        baseCls: 'x-plain',
	        labelWidth: 75,
	        margins:'10 10 5 10',			
			buttonAlign: 'right',
			minButtonWidth: 80,
			buttons:[{
				text: 'OK',
				handler: function(){
					if(validate()) {
						//saveData();
						window.nativeWindow.close();
					}
				}
			},{
				text: 'Cancel',
				handler: function(){ window.nativeWindow.close(); }
			}],				
	        items: [
	        	treeField,
				isPTIShared,
				title,
				description
			]
	    });
	
		var viewport = new Ext.Viewport({
			layout:'border',
			items:[
				tb, 
				form
			]
		});
	}
}


Ext.onReady(function(){
	Ext.BLANK_IMAGE_URL = "../ext-2.1/resources/images/default/s.gif";
    Ext.QuickTips.init();	
	
	/*
	 * Create file category data store
	 */
	getDataObj.getCategories();
	
	/*
	 * Create window and form
	 */
	windowObj.initWindow();
	
	/*
	var msg = Ext.get('msg');
	var task = getTask();
	
	if(task && task.data.completedDate){
		setMsg('This task was completed on ' + task.data.completedDate.format('l, F d, Y'));
	}	
	
	hasReminder.on('check', function(cb, checked){
		reminder.setDisabled(!checked);
		if(checked && !reminder.getValue()){
			reminder.setValue(opener.tx.data.getDefaultReminder(getTask()));
		}
	});
	
	refreshData.defer(10);

	win.visible = true;
	win.activate();
	
	title.focus();
		
	function refreshData(){
		if(!isNew){
			var task = getTask();
			hasReminder.setValue(!!task.data.reminder);
			form.getForm().loadRecord(task);
			setCompleted(task.data.completed);
		}
	}
	
	function saveData(){
		var task;
		if(isNew){
			task = opener.tx.data.tasks.createTask(
				title.getValue(), 
				list.getRawValue(), 
				dueDate.getValue(), 
				description.getValue(),
				completed
			);
		}else{
			task = getTask();
			task.set('completed', completed);
		}
		if(!hasReminder.getValue()){
			reminder.setValue('');
		}
		form.getForm().updateRecord(task);
	}
	
	function setCompleted(value){
		completed = value;
		var cplBtn = Ext.getCmp('cpl-btn');
		if (completed) {
			cplBtn.setText('Mark Active');
			cplBtn.setIconClass('icon-mark-active');
			hasReminder.disable();
			reminder.disable();
		}
		else {
			cplBtn.setText('Mark Complete');
			cplBtn.setIconClass('icon-mark-complete');
			setMsg(null);
			hasReminder.enable();
			reminder.setDisabled(!hasReminder.checked);
		}
	}
	
	function setMsg(msgText){
		var last;
		if(!msgText) {
			msg.setDisplayed(false);
		} else {
			msg.setDisplayed('');
			msg.update(msgText);
		}
		description.anchorSpec.bottom = function(v){
            if(v !== last){
                last = v;
				var h = msg.getHeight();
                return v - 95 - (h ? h + 8 : 0);
            }
        };
		form.doLayout();
	}
	
	function validate(){
		if(Ext.isEmpty(title.getValue(), false)){
			Ext.Msg.alert('Warning', 'Unable to save changes. A subject is required.', function(){
				title.focus();
			});
			return false;
		}
		return true;
	}
	
	function getTask(){
		var t = opener.tx.data.tasks.lookup(taskId);
		if(t){
			//workaround WebKit cross-frame date issue
			fixDateMember(t.data, 'completedDate');
			fixDateMember(t.data, 'reminder');
			fixDateMember(t.data, 'dueDate');
		}
		return t;
	}
	*/
	
});

    

